package com.dao.impl;

import com.bean.Goods;
import com.dao.GoodsDao;
import com.utils.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GoodsDaoImpl implements GoodsDao {
    public static final JdbcTemplate JDBC_TEMPLATE = new JdbcTemplate(DruidUtil.getDataSource());
    @Override
    public List<Goods> seAll() {
        String sql = "select * from goods";
        return JDBC_TEMPLATE.query(sql, new BeanPropertyRowMapper<>(Goods.class));
    }

    /**
     * 执行添加商品操作
     * @param good
     * @return
     */
    @Override
    public boolean add(Goods good) {
        String sql = "insert into goods values (default,?,?,?,?,?,?,?)";
        return JDBC_TEMPLATE.update(sql,good.getGname(),good.getGimg(),good.getGprice(),
                good.getGstock(),good.getMaintainDate(),good.getClassify(),good.getGdescribe())>0;
    }

    @Override
    public boolean del(int gid) {
        String sql = "delete from goods where gid = ?";
        return JDBC_TEMPLATE.update(sql,gid)>0;
    }

    @Override
    public List<Goods> seByOther(Map<String, Object> other) {
        StringBuffer sql = new StringBuffer( "select * from goods");
        List list = new ArrayList();
        if(other.size()>0) {
            sql.append(" where 1=1 ");
            for (String key : other.keySet()) {
                sql.append(" and " + key + " like ? ");
                list.add("%"+other.get(key)+"%");
            }
        }
        return JDBC_TEMPLATE.query(sql.toString(), new BeanPropertyRowMapper<>(Goods.class),list.toArray());
    }

    @Override
    public boolean upGood(Goods goods) {
        String sql = "update goods set gname=?,gimg=?,gprice=?,gstock=?,maintainDate=?,classify=?,gdescribe=? where gid=?";
        return JDBC_TEMPLATE.update(sql,goods.getGname(),goods.getGimg(),goods.getGprice(),
                goods.getGstock(),goods.getMaintainDate(),goods.getClassify(),
                goods.getGdescribe(),goods.getGid())>0;
    }

    @Override
    public boolean delAll(String[] gids) {
        StringBuffer sql = new StringBuffer("delete from goods where 1 = 2 ");
        //遍历需要删除的id数组进行添加元素
        for (String gid : gids) {
            sql.append("or gid = ?");
        }
        return JDBC_TEMPLATE.update(sql.toString(),gids)>0;
    }
}
